import sys

from PyQt6.QtCore import Qt
from PyQt6.QtWidgets import QApplication, QWidget, QTableWidget, QVBoxLayout, QTableWidgetItem, QMenu


class MyWidget(QWidget):
    def __init__(self):
        super(MyWidget, self).__init__()
        self.setWindowTitle('QTableWidget 测试')
        self.resize(500, 300)

        self.tablewidget = QTableWidget()
        self.tablewidget.move(20, 20)
        self.tablewidget.setRowCount(6)
        self.tablewidget.setColumnCount(4)
        self.tablewidget.setHorizontalHeaderLabels(['课程编号', '课程名', '学时', '学分'])

        self.tablewidget.setItem(0, 0, QTableWidgetItem('1A001'))
        self.tablewidget.setItem(0, 1, QTableWidgetItem('Python 程序设计'))
        self.tablewidget.setItem(0, 2, QTableWidgetItem('60'))
        self.tablewidget.setItem(0, 3, QTableWidgetItem('3'))
        self.tablewidget.setItem(1, 0, QTableWidgetItem('1A002'))
        self.tablewidget.setItem(1, 1, QTableWidgetItem('鸿蒙系统开发'))
        self.tablewidget.setItem(1, 2, QTableWidgetItem('80'))
        self.tablewidget.setItem(1, 3, QTableWidgetItem('4'))

        layout = QVBoxLayout()
        layout.addWidget(self.tablewidget)
        self.setLayout(layout)

        # 右键菜单
        self.tablewidget.setContextMenuPolicy(Qt.ContextMenuPolicy.CustomContextMenu)
        self.tablewidget.customContextMenuRequested.connect(self.generateMenu)

    def generateMenu(self, pos):
        row = -1
        for i in self.tablewidget.selectionModel().selection().indexes():
            row = i.row()
        if row < 2:
            menu = QMenu()
            m1 = menu.addAction('课程编号')
            m2 = menu.addAction('课程名')
            m3 = menu.addAction('课程信息')
            action = menu.exec(self.tablewidget.mapToGlobal(pos))
            if action == m1:
                print('课程编号: %s' % self.tablewidget.item(row, 2).text())
            elif action == m2:
                print('课程名: %s' % self.tablewidget.item(row, 1).text())
            elif action == m3:
                print('课程信息: ',
                      self.tablewidget.item(row, 0).text(),
                      self.tablewidget.item(row, 1).text(), end='  ')


if __name__ == '__main__':
    app = QApplication(sys.argv)
    window = MyWidget()
    window.show()
    sys.exit(app.exec())
